import axios, { AxiosInstance } from 'axios'
import { type Config, getRandomIP, getRandomUserAgent } from '../../utils/baseUtils.js'
import axiosRetry from 'axios-retry'
import { HttpsProxyAgent } from 'https-proxy-agent'
import { CrawlerFileUtils } from '../../utils/baseUtils.js'

// unspansh 爬虫配置文件类型
type ConfigUnsplash = Config & {
  proxy: {
    enable: boolean // 是否启用代理
    type: 'http' | 'https' | 'socks5' // 目前只支持 http
    host: string
    port: number
  }
}

const fileUtils = new CrawlerFileUtils<ConfigUnsplash>(import.meta.url)

// =================== 创建一个 axios 实例 ===================
const { type, host, port, enable } = fileUtils.config.proxy
const axiosInstance: AxiosInstance = axios.create({
  timeout: 300000, // 5分钟超时

  // 配置代理
  proxy: false,
  httpsAgent: enable ? new HttpsProxyAgent(`${type}://${host}:${port}`) : undefined,
})

// 自动重试
axiosRetry(axiosInstance, {
  retries: 3, // 重试次数
})

// 请求拦截器
axiosInstance.interceptors.request.use((config) => {
  config.headers['User-Agent'] = getRandomUserAgent()
  config.headers['X-Forwarded-For'] = getRandomIP()
  config.headers['X-Real-IP'] = getRandomIP()
  config.headers['Referer'] = 'https://unsplash.com/s/photos'
  return config
})

export { axiosInstance, fileUtils }
